﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using LynxWiki.DomainModel;

namespace LynxWiki
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            LynxWiki.DomainModel.WikiRoot.RootDirectory = @"WikiRoot\WikiDir";
            LynxWiki.DomainModel.WikiRoot.SiteUrl = ConfigurationManager.AppSettings["SiteUrl"];
            LynxWiki.DomainModel.WikiRoot.IFilterUrl = ConfigurationManager.AppSettings["IFilterUrl"];
            LynxWiki.DomainModel.WikiRoot.EmoticonUrl = ConfigurationManager.AppSettings["EmoticonUrl"];
            LynxWiki.DomainModel.WikiRoot.HostWikiPath = ConfigurationManager.AppSettings["HostWikiPath"];
            LynxWiki.DomainModel.WikiRoot.MaxAttachmentSize = ConfigurationManager.AppSettings["MaxAttachmentSize"];
            if (string.IsNullOrEmpty(LynxWiki.DomainModel.WikiRoot.EmoticonUrl)) {
                LynxWiki.DomainModel.WikiRoot.EmoticonUrl = "/LynxWiki/";
            }
            bool _wikiEmoticons = false;
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DisableWikiEmoticons"])) {
                _wikiEmoticons = Convert.ToBoolean(ConfigurationManager.AppSettings["DisableWikiEmoticons"]);
            }

            Dictionary<System.Net.IPAddress, DateTime> wikiWriteGovernor = new Dictionary<System.Net.IPAddress, DateTime>();

            List<System.Net.IPAddress> wikiGovernorOverrideIP = new List<System.Net.IPAddress>();
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["WikiGovernorOverrideIP"])) {
                string[] ipList = (ConfigurationManager.AppSettings["WikiGovernorOverrideIP"]).Split(',');
                foreach (string item in ipList) {
                    wikiGovernorOverrideIP.Add(System.Net.IPAddress.Parse(item.Trim()));
                }
            }
            List<IPAddressRange> wikiGovernorOverrideIPRange = new List<IPAddressRange>();
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["WikiGovernorOverrideIPRange"])) {
                string[] ipRangeList = ConfigurationManager.AppSettings["WikiGovernorOverrideIPRange"].Split(';');
                foreach (string item in ipRangeList) {
                    string[] ipRange = item.Split('-');
                    wikiGovernorOverrideIPRange.Add(new IPAddressRange(IPAddress.Parse(ipRange[0].Trim()), IPAddress.Parse(ipRange[1].Trim())));
                }
            }
            List<System.Net.IPAddress> wikiBlacklistIP = new List<System.Net.IPAddress>();
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["WikiBlacklistIP"])) {
                string[] ipList = (ConfigurationManager.AppSettings["WikiBlacklistIP"]).Split(',');
                foreach (string item in ipList) {
                    wikiBlacklistIP.Add(System.Net.IPAddress.Parse(item.Trim()));
                }
            }
            List<IPAddressRange> wikiBlacklistIPRange = new List<IPAddressRange>();
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["WikiBlacklistIPRange"])) {
                string[] ipRangeList = ConfigurationManager.AppSettings["WikiBlacklistIPRange"].Split(';');
                foreach (string item in ipRangeList) {
                    string[] ipRange = item.Split('-');
                    wikiBlacklistIPRange.Add(new IPAddressRange(IPAddress.Parse(ipRange[0].Trim()), IPAddress.Parse(ipRange[1].Trim())));
                }
            }
            int governorWriteFreq = 60;
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["GovernorWriteFreq"])) {
                int.TryParse(ConfigurationManager.AppSettings["GovernorWriteFreq"], out governorWriteFreq);
            }
            HttpContext.Current.Application.Add("__DisableWikiEmoticons", _wikiEmoticons);
            HttpContext.Current.Application.Add("__WikiWriteGovernor", wikiWriteGovernor);
            HttpContext.Current.Application.Add("__WikiGovernorOverrideIP", wikiGovernorOverrideIP);
            HttpContext.Current.Application.Add("__WikiGovernorOverrideIPRange", wikiGovernorOverrideIPRange);
            HttpContext.Current.Application.Add("__WikiBlacklistIP", wikiBlacklistIP);
            HttpContext.Current.Application.Add("__WikiBlacklistIPRange", wikiBlacklistIPRange);
            HttpContext.Current.Application.Add("__GovernorWriteFreq", governorWriteFreq);
            
            List<string> validLicenses = new List<string>();
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ValidLicense"])) {
                validLicenses = ConfigurationManager.AppSettings["ValidLicense"].Split(':').ToList();
            }
            HttpContext.Current.Application.Add("__ValidLicenseList", validLicenses);
            HttpContext.Current.Application.Add("__CreativeCommons", "off");
            HttpContext.Current.Application.Add("__DefaultLicense", string.Empty);
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CreativeCommons"])) {
                HttpContext.Current.Application.Remove("__CreativeCommons");
                HttpContext.Current.Application.Add("__CreativeCommons", ConfigurationManager.AppSettings["CreativeCommons"]);
            }
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DefaultLicense"])) {
                HttpContext.Current.Application.Remove("__DefaultLicense");
                HttpContext.Current.Application.Add("__DefaultLicense", ConfigurationManager.AppSettings["DefaultLicense"]);
            }
            Parser.ParserEngine.Initialize();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            HttpContext.Current.Session.Add("__MyWorkingDir", new WorkingDirectory(@"~\WikiRoot\WikiDir"));
        }

    }
}